<?php

namespace App\Http\Middleware;

use App\Response;
use Closure;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;

class Validate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle( $request, Closure $next )
    {
        // 当前执行路由
        $execute_router = substr( $request->route()->getAction( 'controller' ), 21 );
        
        // 获取行为
        $action = explode( '@', $execute_router );

        // 获取控制器
        $controller = $action[ 0 ];

        // 获取执行方法
        $method = $action[ 1 ];

        // 获取输入数据
        $params = $request->input();

        // 自动验证器名
        $validate_class = '\App\Validator\\' . $controller;
        
        // 存在验证器和场景执行自动验证
        if( class_exists( $validate_class ) )
        {
            // 初始化验证器
            $validate = new $validate_class;

            // 验证场景
            if( $validate->hasScene( $method ) )
            {
                $messages = $validate->messages();   // 验证信息
                $rules = $validate->getSceneRule( $method );    // 验证规则
                
                // 执行验证
                $valid_result = Validator::make( $params, $rules, $messages );
                
                // 验证结果失败
                if( $valid_result->fails() )
                {
                    // 返回响应数据
                    return Response::json( [ 'code' => 10002, 'message' => 'error data', 'result' => $valid_result->errors()->first() ] );
                }
            }
        }

        return $next( $request );
    }
}